package com.eco.fanliapp.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.eco.fanliapp.common.response.ServerResponse;
import com.eco.fanliapp.dao.SyGoldExchangeMapper;
import com.eco.fanliapp.service.*;
import com.eco.fanliapp.dao.SyUserMoneyMapper;
import com.eco.fanliapp.entity.SyGoldExchange;
import com.eco.fanliapp.entity.SyUserMoney;
import com.eco.fanliapp.utils.EmojiUtil;
import javassist.expr.NewArray;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author jobob
 * @since 2019-08-07
 */
@Service
public class SyGoldExchangeServiceImpl extends ServiceImpl<SyGoldExchangeMapper, SyGoldExchange> implements ISyGoldExchangeService{
    private static final Logger log = LoggerFactory.getLogger(SyGoldExchangeServiceImpl.class);
    @Autowired
    private SyGoldExchangeMapper syGoldExchangeMapper;
    @Autowired
    private SyUserMoneyMapper syUserMoneyMapper;
    @Autowired
    private ISyUserMoneyLogService syUserMoneyLogService;
    @Autowired
    private ISyUserMoneyService iSyUserMoneyService;
    @Autowired
    private RedisLockService redisLockService;

    /**
     * 兑换规则
     * @param userId
     * @return
     */
    @Override
    public ServerResponse getAppTaskGoldExchangeRules(Long userId) {
        HashMap map = new HashMap();
        QueryWrapper<SyUserMoney> queryWrapper = new QueryWrapper();
        queryWrapper.eq("user_id", userId);
        SyUserMoney syUserMoney = syUserMoneyMapper.selectOne(queryWrapper);
        if(syUserMoney != null){
            Integer goldBalanceAmount = syUserMoney.getGoldBalanceAmount();
            Integer number = goldBalanceAmount/100;
            BigDecimal exchangeMoney = BigDecimal.valueOf(number*0.1);
            map.put("goldBalance",goldBalanceAmount);
            map.put("exchangeMoney",exchangeMoney);
            map.put("exchangeRules","100金币可兑换现金0.1元");

            return ServerResponse.createBySuccess("金币兑换现金",map);
        }else {
            map.put("goldBalance",0);
            map.put("exchangeMoney",0);
            map.put("exchangeRules","100金币可兑换现金0.1元");

            return ServerResponse.createBySuccess("金币兑换现金",map);
        }
    }

    /**
     * 老版本兑换
     * @param userId
     * @param exchangeNumber
     * @param remark
     * @return
     */
    @Override
    public ServerResponse getAppTaskGoldExchange(Long userId, Integer exchangeNumber,String remark) {
        QueryWrapper<SyUserMoney> queryWrapper = new QueryWrapper();
        queryWrapper.eq("user_id", userId);
        SyUserMoney syUserMoney = syUserMoneyMapper.selectOne(queryWrapper);
        if(syUserMoney != null) {
            if(exchangeNumber>syUserMoney.getGoldBalanceAmount() || exchangeNumber<10){
                return ServerResponse.createByError("兑换失败",null);
            }
            Integer goldBalanceAmount = syUserMoney.getGoldBalanceAmount();
            Integer number = exchangeNumber / 10;
            BigDecimal exchangeMoney = BigDecimal.valueOf(number * 0.01);

            //兑换后金币剩余个数
            Integer newgoldBalanceAmount = goldBalanceAmount - number * 10;
            //修改用户的剩余金币
            SyUserMoney userMoney = new SyUserMoney();
            userMoney.setTableId(syUserMoney.getTableId());
            userMoney.setGoldBalanceAmount(newgoldBalanceAmount);
            userMoney.setCashBalanceAmount(syUserMoney.getCashBalanceAmount().add(exchangeMoney));
            userMoney.setCashTotalAmount(syUserMoney.getCashTotalAmount().add(exchangeMoney));
            //根据tableid修改用户剩余金币个数，现金余额
            int i = syUserMoneyMapper.updateById(userMoney);

            //账户金额发生变动，添加账户变更日志
            Integer logStatus = 0;//加钱
            syUserMoneyLogService.addSyUserMoneyLog(userId,syUserMoney.getCashBalanceAmount(),exchangeMoney,remark,null,logStatus);


            if (i > 0) {
                //金币兑换记录
                SyGoldExchange syGoldExchange = new SyGoldExchange();
                syGoldExchange.setUserId(userId);
                syGoldExchange.setUserMoneyId(syUserMoney.getTableId());
                syGoldExchange.setExchangeType(1);
                syGoldExchange.setExchangeStatus(1);
                syGoldExchange.setExchangeGoldAmount(exchangeNumber-newgoldBalanceAmount);
                syGoldExchange.setExchangeCashAmount(exchangeMoney);
                syGoldExchange.setExchangeProportion(10);
                syGoldExchange.setExchangeRemainingGoldAmount(newgoldBalanceAmount);

                int ii = syGoldExchangeMapper.insert(syGoldExchange);

                return ServerResponse.createBySuccess("兑换成功",exchangeMoney);
            }
            return ServerResponse.createByError("兑换失败",exchangeMoney);
        }
        return ServerResponse.createByError("兑换失败",null);
    }


    /**
     * 金币兑换money
     * @param userId
     * @param remark
     * @return
     */
    @Override
    @Transactional(rollbackFor = {RuntimeException.class, Exception.class})
    public BigDecimal getUserTaskGoldExchangeMoney(Long userId,String remark) {
        SyUserMoney syUserMoney = iSyUserMoneyService.selectByUserId(userId);
        if (syUserMoney != null && syUserMoney.getGoldBalanceAmount() >= 10) {
            //获取可兑换金币数量
            Integer goldBalanceAmount = syUserMoney.getGoldBalanceAmount();
            Integer number = goldBalanceAmount / 10;
            BigDecimal exchangeMoney = BigDecimal.valueOf(number * 0.01);
            //兑换后金币剩余个数
            Integer newgoldBalanceAmount = goldBalanceAmount - number * 10;
            //插入兑换日志
            //金币兑换记录
            SyGoldExchange syGoldExchange = new SyGoldExchange();
            syGoldExchange.setUserId(userId);
            syGoldExchange.setUserMoneyId(syUserMoney.getTableId());
            syGoldExchange.setExchangeType(1);
            syGoldExchange.setExchangeStatus(1);
            syGoldExchange.setExchangeGoldAmount(goldBalanceAmount-newgoldBalanceAmount);
            syGoldExchange.setExchangeCashAmount(exchangeMoney);
            syGoldExchange.setExchangeProportion(10);
            syGoldExchange.setExchangeRemainingGoldAmount(newgoldBalanceAmount);

            int exchangeStatus = syGoldExchangeMapper.insert(syGoldExchange);
            int balanceStatus = 0;
            if(exchangeStatus > 0){
                String redisKeyStr = "user_money_cash_gold_lock_"+userId;
                //redis锁-时间
                long times = System.currentTimeMillis() + 1000 * 3;
                //获取锁
                if (!redisLockService.lock(redisKeyStr, times + "")) {
                    return null;//锁存在
                }
                //插入成功，修改金币和现金数量
                SyUserMoney userMoney = new SyUserMoney();
                userMoney.setTableId(syUserMoney.getTableId());
                userMoney.setGoldBalanceAmount(newgoldBalanceAmount);
                userMoney.setCashBalanceAmount(syUserMoney.getCashBalanceAmount().add(exchangeMoney));
                userMoney.setCashTotalAmount(syUserMoney.getCashTotalAmount().add(exchangeMoney));
                //根据tableid修改用户剩余金币个数，现金余额  获取锁
                balanceStatus = syUserMoneyMapper.updateById(userMoney);

          }
            //账户金额发生变动，添加账户变更日志
            if(balanceStatus>0 && exchangeMoney.doubleValue() > 0){
                syUserMoneyLogService.addSyUserMoneyLog(userId,syUserMoney.getCashBalanceAmount(),exchangeMoney,remark,null,0);
                return exchangeMoney;
            }
        }else {
            return null;
        }
        return null;
    }
}
